package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import vo.StockInfo;
import vo.UserInterest;

public class FileHandlerImpl implements FileHandler {

	/**
	 * This func gets stock information from the given interfaces path. If
	 * interfaces don't exit,or it has a illegal/malformed format, return NULL. The
	 * filepath can be a relative path or a absolute path
	 *
	 * @param filePath
	 * @return the Stock information array from the interfaces,or NULL
	 */
	@Override
	public StockInfo[] getStockInfoFromFile(String filePath) {
		// TODO: write your code here
		try {
			FileInputStream file_fi = new FileInputStream(filePath);
			InputStreamReader file_sr = new InputStreamReader(file_fi, "UTF-8");
			BufferedReader file = new BufferedReader(file_sr);

			boolean eof = false;

			final int MAXSI = 60;
			StockInfo[] siArray = new StockInfo[MAXSI];
			ArrayList<StockInfo> siArraylist = new ArrayList<StockInfo>();

			while (!eof) {
				String line = file.readLine();
				if (line == null) {
					eof = true;
				} else {
					StockInfo temp = new StockInfo();
					String[] data = line.split("\t");
					temp.setID(data[0]);
					temp.setTITLE(data[1]);
					temp.setAUTHOR(data[2]);
					temp.setDATE(data[3]);
					temp.setLASTUPDATE(data[4]);
					temp.setCONTENT(data[5]);
					temp.setANSWERAUTHOR(data[6]);
					temp.setANSWER(data[7]);
					siArraylist.add(temp);
				}
			}
			file.close();
			int i = -1;
			for (StockInfo temp : siArraylist) {
				if (i == -1) {
					i++;
					continue;
				}
				siArray[i] = temp;
				i++;
			}
			return siArray;
		} catch (IOException e) {
			System.out.println("Error: " + e.getMessage());
			return null;
		}
	}
}
